package com.itheima.service.imple;

//import com.itheima.service.SearchService;
import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import com.hmall.common.dto.PageDTO;
import com.itheima.pojo.RequestParams;
import com.itheima.service.SearchabcService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceImpl implements SearchabcService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public List<String> AutoSuggestion(String key) {
        List<String> list;
        SearchRequest request = new SearchRequest("hmmall");
        request.source().suggest(new SuggestBuilder()
                .addSuggestion("suggestion", SuggestBuilders.completionSuggestion("suggestion")
                        .skipDuplicates(true)
                        .prefix(key).size(10)
                ));
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestion = suggest.getSuggestion("suggestion");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            list = new ArrayList<>();

            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hmmall");
            buildBasicQuery(params, request);
            request.source().size(0);
            buildAggregation(request);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            HashMap<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> categoryList = getAggByName(aggregations,"categoryAgg");
            result.put("category", categoryList);
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            result.put("brand", brandList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> basicSearch(RequestParams params) {
        try {
            SearchRequest request = new SearchRequest("hmmall");
            buildBasicQuery(params, request);
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page-1)*size).size(size);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private PageDTO<ItemDoc> handleResponse(SearchResponse response){
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        SearchHit[] hits = searchHits.getHits();
        PageDTO<ItemDoc> pageDTO = new PageDTO<>();
        List<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(json, ItemDoc.class);
            itemDocs.add(itemDoc);
        }
        pageDTO.setList(itemDocs);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    private void buildBasicQuery(RequestParams params,SearchRequest request){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String key = params.getKey();
        if(key==null||"".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        if(params.getCategory()!=null&&!params.getCategory().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        if(params.getBrand()!=null&&!params.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        if(params.getMinPrice()!=null&&params.getMaxPrice()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
            .gte(params.getMinPrice()*100)
            .lte(params.getMaxPrice()*100));
        }
        request.source().query(boolQuery);
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(10)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(10)
        );
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

}
